// import router from '@/router'
import axios from 'axios'
import {ElMessage} from "element-plus";

// import store from '../store'
// import {
//     getToken,
//     removeToken
// } from '@/utils/auth'
import packageJson from '@/../package.json'

// import context from '../main'
const version = packageJson.version
const domain = "http://192.168.27.147:28308/";
// mock请求头
const devMockAxios = axios.create({
    baseURL: domain,
    timeout: 200000
})

// online请求头
const devOnlineAxios = axios.create({
    baseURL: domain,
    timeout: 200000
})

// prod请求头
const prodOnlineAxios = axios.create({
    baseURL: domain,
    timeout: 200000
})

const SERVERCODE = {
    'success': 40001, // 成功
    'nologin': 40005, // 未登录
    'noPermission': 40006, // 无权限
    'overdue': 40029, // token已经过期
    'changePassWord': 40008, // 修改密码
    'notFound': 400012, // 找不到接口
    'upgrade': 400013, // 强制更新
    'multiCompany': 40033 // 强制更新
}
// 发出请求
// 返回promise
function request(options, method) {
    // 判断是否已保存token，并在每次请求头部添加token
    // 去除字符串空格
    // 没有token则取消请求
    // const token = true;
    // const loginReg = options.url.indexOf('login') !== -1
    // const resetPasswordReg = options.url.indexOf('resetPassword') !== -1
    // const logoutReg = options.url.indexOf('logout') !== -1
    // const sendResetPasswordVerificationCodeReg = options.url.indexOf('sendResetPasswordVerificationCode') !== -1
    // if (!(loginReg || sendResetPasswordVerificationCodeReg || resetPasswordReg || logoutReg)) {
    //     if (!token) {
    //         return new Promise((resolve, reject) => {
    //             reject()
    //         })
    //     }
    // }
    // 去除前后空格
    for (const key in options.params) {
        if (typeof options.params[key] === 'string') options.params[key] = options.params[key].trim()
    }
    // 所有请求入口带上请求时间
    if (!options.params) options.params = {}
    options.params.timestamp = Math.round(new Date().getTime() / 1000).toString()
    // 设置请求头设置
    const axiosOption = {
        method: method || 'post',
        url: options.url,
        responseType: 'json',
        headers: {
            mac: 'DE-E9-94-28-A6-53'// 写死mac地址
        }
    }
    // if (context) {
    //     axiosOption.cancelToken = context.source.token
    // }

    // 根据不同的请求方式封装数据
    switch (axiosOption.method) {
        case 'get':
            axiosOption.params = options.params
            break
        case 'post': {
            axiosOption.data = options.params
            break
        }
        case 'upload': {
            const formData = new FormData()
            for (const key in options.params) {
                formData.append(key, options.params[key])
            }
            axiosOption.data = formData
            break
        }
    }

    // 根据不同环境设施请求头
    let requestAxios = prodOnlineAxios;
    // if (process.env.NODE_ENV === 'production') {
    //     requestAxios = prodOnlineAxios
    // } else {
    //     if (options.type === 1) {
    //         requestAxios = devMockAxios
    //     } else {
    //         requestAxios = devOnlineAxios
    //     }
    // }
    setInterceptors(requestAxios)
    // 状态码判断

    return new Promise((resolve, reject) => {
        // 发出请求
        requestAxios.request(axiosOption).then(response => {
            const data = response.data
            // 请求正常
            if (response.status === 200) {
                switch (Number(data.code)) {
                    case SERVERCODE.success: {
                        resolve(data)
                        break
                    }
                    case SERVERCODE.multiCompany:
                    case SERVERCODE.nologin: {
                        ElMessage.error(data.message || '请重新登录')
                        // router.push('/login')
                        reject(data)
                        // removeToken()
                        break
                    }
                    case SERVERCODE.noPermission:
                    case SERVERCODE.overdue: {
                        // if (getToken()) {
                        //     ElMessage.error('无权限或者token已经过期')
                        //     removeToken()
                        // }
                        // store.dispatch('FedLogOut').then(_ => {
                        //     router.push('/login')
                        // })
                        break
                    }
                    case SERVERCODE.upgrade: {
                        reject(data)

                        ElMessage.error(data.message || 'error')
                        setTimeout(() => {
                            window.location.reload()
                        }, 2000)
                        break
                    }
                    case SERVERCODE.changePassWord: {
                        // reject(data)
                        // ElMessage.error(data.message || '请修改密码')
                        // setTimeout(() => {
                        //     router.push('/change_password')
                        // }, 2000)
                        break
                    }
                    case 40067: {
                        console.log('data.message', data.message)

                        ElMessage.error(
                            {
                                message: data.message || 'error',
                                duration: 5000
                            }
                        )
                        reject(data)
                        break
                    }
                    default:
                        ElMessage.error(data.message || 'error')
                        reject(data)
                        break
                }
            } else if (response.status === 404) {
                ElMessage.error('404 not found')
                reject(data)
            } else {
                if (response) ElMessage.error(response || 'error')
                reject(response)
            }
        }).catch(error => {
            reject(error.response || error)
        })
    }).catch((err) => {
        // alert(err)
    })

}

// get请求
function get(options) {
    return request(options, 'get')
}

// post请求
function post(options) {
    return request(options, 'post')
}

// upload请求
function upload(options) {
    return request(options, 'upload')
}

// download下载
function download(options) {
    const token = getToken()
    if (!options.params) {
        options.params = {
            token
        }
    }
    if (options.params.token == null) options.params.token = token
    options.params.timestamp = Math.round(new Date().getTime() / 1000).toString()
    return new Promise((resolve, reject) => {
        const axiosOption = {
            method: 'post',
            url: options.url,
            timeout: options.timeout || 60000,
            responseType: 'json',
            cancelToken: options.cancelToken
        }
        axiosOption.data = options.params

        axios(axiosOption)
            .then(response => {
                if (response.status === 200) {
                    resolve(response)
                } else {
                    ElMessage.error('操作失败，请重试！')
                    reject(response)
                }
            }).catch(error => {
            if (!axios.isCancel(error)) {
                ElMessage.error('操作失败，请重试！')
                reject(error)
            }
        })
    })
}

// 设置拦截器
function setInterceptors(val) {
// 请求拦截器
    val.interceptors.request.use(
        config => {
            // 设置请求头格式
            // post 请求时进行json格式序列化
            config.headers['Content-Type'] = 'application/json'
            config.headers['Authorization'] = 'Bearer ' + false || ''
            // config.headers['Platform'] = 'Web'
            config.headers['Version'] = version
            if (config.method === 'upload') {
                config.method = 'post'
                config.headers['Content-Type'] = 'multipart/form-data;charset=UTF-8'
            }
            return config
        },
        error => {
            // Do something with request error
            console.log('error', error) // for debug
            return Promise.reject(error)
        }
    )

    // 返回拦截
    val.interceptors.response.use(function (response) {
        return response
    }, function (error) {
        // 对响应错误做处理...
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
            ElMessage.error('请求超时！')
        }
        return error
    })
}

const ajax = {
    get,
    post,
    upload,
    download
}

export default ajax
